// src/main/java/index/SessionCounterListener.java
package index;

import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
import java.util.concurrent.atomic.AtomicInteger;

@WebListener
public class SessionCounterListener implements HttpSessionListener {
    private final AtomicInteger activeSessions = new AtomicInteger();

    @Override
    //会话创建事件处理方法
    public void sessionCreated(HttpSessionEvent se) {
        activeSessions.incrementAndGet();
        updateSessionCount(se);
    }

    @Override
    //会话销毁事件处理方法
    public void sessionDestroyed(HttpSessionEvent se) {
        activeSessions.decrementAndGet();
        updateSessionCount(se);
    }
    //更新会话计数
    private void updateSessionCount(HttpSessionEvent se) {
        se.getSession().getServletContext().setAttribute("activeSessions", activeSessions.get());
    }
}
